package server.response;

/**
 * @author cg
 * @date 2023/6/7 14:54
 */

import java.util.Map;

/**
 * 使用构建者模式创建响应请求头
 */
public class ResponseHeader {
    String statusCode;
    String contentType;
    String contentLength;
    String setCookie;

    private ResponseHeader(Builder builder) {
        this.statusCode = builder.statusCode;
        this.contentLength = builder.contentLength;
        this.setCookie = builder.setCookie;
        this.contentType = builder.contentType;
    }

    @Override
    public String toString() {
        return statusCode + contentType + setCookie + contentLength ;
    }

    public static class Builder {
        String statusCode = "";
        String contentType = "";
        String contentLength = "";
        String setCookie = "";


        public Builder statusCode(String statusCode) {
            this.statusCode = statusCode;
            return this;
        }

        public Builder contentType(String contentType) {
            this.contentType = "Content-Type: " + contentType + ";charset=utf-8\n";
            return this;
        }

        public Builder setCookie(Map<String,String> cookieMap) {
            this.setCookie = "Set-Cookie: " + resolve(cookieMap) + "\n";
            return this;
        }

        private String resolve(Map<String, String> cookieMap) {
            if (cookieMap.isEmpty()) return "";
            StringBuffer sb = new StringBuffer();
            for (String key :cookieMap.keySet()) {
                sb.append(key).append("=").append(cookieMap.get(key)).append(";");
            }
            return sb.substring(0, sb.length() - 1);
        }

        public Builder contentLength(String contentLength) {
            this.contentLength = "Content-Length: " + contentLength + "\n" +
                    "\r\n";
            return this;
        }

        public ResponseHeader build() {
            return new ResponseHeader(this);
        }
    }
}
